<template>
	<div class="lx-container">
		<div class="mode-title">
			<div class="mode-left">
				<el-divider direction="vertical"></el-divider>
				创建培训
			</div>
			
		</div>
		<el-form ref="editForm" :model="editForm" :rules="editRules" label-width="120px" class="edit-form">
			<el-form-item label="培训主题" prop="trainTitle">
				<el-input maxlength="30" v-model="editForm.trainTitle"></el-input>
			</el-form-item>
			<el-form-item label="培训类型" prop="trainCategoryId">
				<el-select v-model="editForm.trainCategoryId" filterable placeholder="请选择">
					<el-option v-for="type in trainTypeList" :key="type.id" :label="type.categoryName" :value="type.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="封面" prop="pictureUrl">
				<file-uploader ref="fUpl" :defaultUrl="editForm.pictureUrl" @onSuccess="imgSuccess" :buttonWidth="214"
				 :buttonHeight="160"></file-uploader>
			</el-form-item>
			<el-form-item label="报名有效时间" prop="enrollTime">
				<el-date-picker v-model="editForm.enrollTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd hh:mm:ss"
					:picker-options="pickerOptions" :unlink-panels="true">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="培训简介" prop="trainIntroduction">
				<ueditor ref="myUeditor" v-model="editForm.trainIntroduction"></ueditor>
			</el-form-item>
		</el-form>
		<div style="width:100% ;height: 16px;background-color: #F9FAFC;"></div>
		<div class="mode-title">
			<div class="mode-left">
				<el-divider direction="vertical"></el-divider>
				培训安排
			</div>
			<el-button size="small" type="primary" @click="openPlanForm">添加培训计划</el-button>
		</div>
		<div class="lx-table">
			<lx-table ref="myTable" :tableData="trainPlanList" :tableCols="tableCols"  isIndex :isPagination="false">
			</lx-table>
		</div>
		<div class="edit-page-bottom-buttom-bars">
			<el-button type="success" @click="onSave">保存</el-button>
			<el-button type="primary" @click="onSubmit">发布</el-button>
			<el-button @click="cancle">取消</el-button>
		</div>
		<el-dialog title="添加培训计划" :visible.sync="planFormVisible" v-if="planFormVisible" width="808px" @close="closePlanForm" destroy-on-close
		:close-on-click-modal="false" :close-on-press-escape="false">
			<el-form :model="planForm" :rules="planRules" ref="planForm" label-width="100px" >
				<el-form-item label="培训主题" prop="trainCourseName">
					<el-input maxlength="30" v-model="planForm.trainCourseName"></el-input>
				</el-form-item>
				<el-form-item label="培训时间" prop="trainTime">
					<el-date-picker v-model="planForm.trainTime" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" value-format="yyyy-MM-dd hh:mm:ss"
						:picker-options="pickerOptions" :unlink-panels="true">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="限制人数" prop="memberCount">
					<el-input  v-model="planForm.memberCount" style="width: 208px;" oninput="if(value.length > 9)value = value.slice(0, 9)"></el-input>
				</el-form-item>
				<el-form-item label="主讲人" prop="expertName">
					<el-input maxlength="30" v-model="planForm.expertName" style="width: 208px;"></el-input>
				</el-form-item>
				<el-form-item label="主讲人简介" prop="trainCourseIntroduction">
					<el-input maxlength="200" type="textarea" v-model="planForm.trainCourseIntroduction" show-word-limit></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closePlanForm">取 消</el-button>
				<el-button type="success" @click="submitPlanForm" >确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import FileUploader from "@/components/FileUploader.vue"
	import Ueditor from "@/components/Ueditor.vue"
	import LxTable from "@/components/LxTable.vue"
	import {
		mapActions
	} from "vuex"
	export default {
		components: {
			"file-uploader": FileUploader,
			"ueditor": Ueditor,
			"lx-table": LxTable
		},
		async mounted() {
			let _this = this;
			//初始化窗口
			let params = _this.$store.state.pageParams; //传入到新建题目的查询参数，新建题目不修改直接返回
			if (!params || JSON.stringify(params) == "{}") {
				_this.$message.error("参数有误");
				setTimeout(() => {
					_this.cancle();
				}, 300)
				return;
			}
			_this.queryParams = params.queryParams;
			_this.trainTypeList = params.trainTypeList;
			if (params.data) {
				let editForm =  params.data;
				let enrollTime = [];
				if(editForm.enrollStartTime && editForm.enrollEndTime){
					enrollTime = [editForm.enrollStartTime,editForm.enrollEndTime]
				}
				editForm.enrollTime = enrollTime;
				_this.editForm = editForm;
				await _this.getPlanList();
			}
		},
		data() {
			return {
				pickerOptions: {
					//限制可选日期
					disabledDate(time) {
						return time.getTime() < Date.now() - 8.64e7;
					}
				}, 
				editForm: {
					id: null,
					trainTitle: '',
					trainCategoryId: null,
					pictureUrl: "",
					trainIntroduction: "",
					enrollTime: [],
					urlList: []
				},
				editRules:{
					trainTitle: [{
						required: true,
						message: '请输入培训主题',
						trigger: 'blur'
					}],
					trainCategoryId: [{
						required: true,
						message: '请选择培训类型',
						trigger: 'change'
					}],
					pictureUrl: [{
						required: true,
						message: '请上传封面',
						trigger: 'change'
					}],
					enrollTime: [{
						required: true,
						message: '请选择报名有效时间',
						trigger: 'change'
					}],
					trainIntroduction: [{
						required: true,
						message: '请输入培训简介',
						trigger: 'blur'
					}],
				},
				queryParams: null,
				trainTypeList:[],
				planForm:{
					trainCourseName: "",
					expertName: "",
					trainTime:[],
					memberCount: null,
					trainCourseIntroduction: ""
				},
				planRules:{
					trainCourseName: [{
						required: true,
						message: '请输入培训主题',
						trigger: 'blur'
					}],
					expertName: [{
						required: true,
						message: '请输入主讲人姓名',
						trigger: 'blur'
					}],
					memberCount: [{
						required: true,
						message: '请输入限制人数',
						trigger: 'blur'
					}],
					trainTime: [{
						required: true,
						message: '请选择培训时间',
						trigger: 'change'
					}],
					trainCourseIntroduction: [{
						required: true,
						message: '请输入讲师简介',
						trigger: 'blur'
					}],
				},
				editPlanIndex:-1,
				trainPlanList:[],
				tableCols:[{
						label: '主题',
						prop: 'trainCourseName',
						align: "center"
					},
					{
						label: '主讲人',
						prop: 'expertName',
						align: "center"
					},
					{
						label: '限制人数(人)',
						prop: 'memberCount',
						align: "center"
					},
					{
						label: '培训时间',
						prop: 'trainTime',
						align: "center",
						formatter: (row) => {
							return row.trainStartTime +" - " + row.trainEndTime;
						},
						width: 320,
					},
					{
						label: '主讲人简介',
						type: "html",
						prop: 'trainCourseIntroduction'
					},
					{
						label: '操作',
						type: 'Button',
						btnList: [
							{
								type: 'text',
								label: '编辑',
								handle: (that, row,index) => this.editPlan(row,index)
							},
							{
								type: 'text',
								label: '删除',
								handle: (that, row,index) => this.del(row,index)
							},
							{
								type: 'text',
								label: '上移',
								disabled:(row,index) => {return index == 0},
								handle: (that, row,index) => this.move(index,true)
							},
							{
								type: 'text',
								label: '下移',
								disabled:(row,index) => {
									return index == (this.trainPlanList.length - 1)
								},
								handle: (that, row,index) => this.move(index,false)
							}
						
						],
						width: 200,
						align: "center"
					},
				],
				planFormVisible:false
			}

		},
		watch:{
			"planForm.memberCount"(val) {
				if(!val){
					return
				}
				this.planForm.memberCount = String(val).replace(/\D/g, '');
			}
		},
		methods: {
			imgSuccess(response, file, fileList) {
				this.editForm.pictureUrl = file.url;
			},
			openPlanForm(){
				this.planFormVisible = true;
			},
			resetPlanForm(){
				this.editPlanIndex = -1;
				this.planForm = {
					trainCourseName: "",
					expertName: "",
					trainTime:[],
					memberCount: null,
					trainCourseIntroduction: ""
				}
			},
			async getPlanList(){
				let _this = this;
				let id = _this.editForm.id;
				let ret = await _this.$api.selectTrainPlanByTrainId(id);
				if (ret) {
					let list = ret.list;
					if(list && list.length > 0){
						list.map(el=>{
							let trainTime = [];
							if(el.trainStartTime && el.trainEndTime){
								trainTime = [el.trainStartTime,el.trainEndTime]
							}
							el.trainTime = trainTime;
						})
						console.log(list);
						_this.trainPlanList = list;
					}
				}
			},
			closePlanForm(){
				this.resetPlanForm();
				this.planFormVisible = false;
			},
			submitPlanForm(){
				let _this = this;
				_this.$refs.planForm.validate(async (valid) => {
					if (valid) {
						let planForm = _this.planForm;
						let trainTime = planForm.trainTime;
						planForm.trainStartTime = trainTime[0];
						planForm.trainEndTime = trainTime[1];
						let editPlanIndex = _this.editPlanIndex;
						if(editPlanIndex != -1){
							//编辑
							_this.$set(this.trainPlanList,editPlanIndex,planForm);
						}else{
							//新增	
							_this.trainPlanList.push(planForm);
						}
						_this.closePlanForm();
					} else {
						return false;
					}
				})
			},
			editPlan(data,index){
				this.editPlanIndex = index;
				this.planForm = data;
				this.planFormVisible = true;
			},
			move(index,flag){
				let trainPlanList = this.trainPlanList;
				let obj = trainPlanList[index];
				let tempIndex ;
				if(flag){
					if(index == 0){
						return;
					}
					//上移
					tempIndex = index - 1;
				}else{
					//下移
					if(index == trainPlanList.length -1){
						return;
					}
					tempIndex = index + 1
				}
				let temp = trainPlanList[tempIndex];
				this.$set(this.trainPlanList,tempIndex,obj);
				this.$set(this.trainPlanList,index,temp);
			},
			del(row,index){
				let _this = this;
				_this.$confirm('确定要删除当前数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					_this.trainPlanList.splice(index,1);
					console.log(_this.trainPlanList)
				}).catch(() => {
				
				})
			},
			onSave(){
				this.submitToServer(0);
			},
			onSubmit(){
				let _this = this;
				_this.$refs.editForm.validate(async (valid) => {
					if (valid) {
						if(_this.trainPlanList.length == 0){
							_this.$message.error("请添加培训计划");
							return false;
						}
						_this.submitToServer(1);
					} else {
						return false;
					}
				})
			},
			async submitToServer(isIssue){
				let _this = this;
				let editForm = _this.editForm;
				let enrollTime = editForm.enrollTime;
				if(enrollTime.length > 0){
					editForm.enrollStartTime = enrollTime[0];
					editForm.enrollEndTime = enrollTime[1];
				}
				let trainPlanList = _this.trainPlanList;
				if(trainPlanList.length > 0){
					editForm.trainPlanList = trainPlanList;
				}
				editForm.isIssue = isIssue;
				let ret = _this.$api.insertTrainAndTrainPlan(_this.editForm);
				if(ret){
					_this.$message.success("提交成功");
					setTimeout(()=>{
						_this.cancle();
					},500)
				}
			},
			cancle(){
				this.setPageParams({
					queryParams: this.queryParams
				});
				this.$router.push({
					name: "TrainManager"
				});
			},
			...mapActions(["setPageParams"])
		}
	}
</script>

<style scoped="scoped" lang="scss">
	.lx-container {
		width: 100%;
		@include flex-column(flex-start, flex-start);
		box-sizing: border-box;

		.mode-title {
			width: 100%;
			height: 56px;
			border-bottom: solid 1px #EBEEF6;
			box-sizing: border-box;
			padding:0 16px;
			@include flex-row(space-between, center);
			color: $mainColor;
			font-size: 16px;
			font-weight: bolder;

			.mode-left{
				@include flex-row(flex-start, center);
			}
			.el-divider--vertical {
				width: 3px;
				background-color: $mainColor;
				margin-right: 8px;
			}
			
		}

		.edit-form {
			width: 1000px;
			margin-top: 24px;
		}
		.lx-table{
			padding: 24px;
			box-sizing: border-box;
		}
	}
</style>
